import axios from 'axios'
import { API_CONFIG } from '@/config/index.js'

// 创建axios实例
const api = axios.create({
  baseURL: API_CONFIG.BASE_URL,
  timeout: API_CONFIG.TIMEOUT,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 可以在这里添加token等认证信息
    const token = localStorage.getItem('token')
    const userId = localStorage.getItem('userId')
    
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    } else if (userId) {
      // 如果没有token但有userId，可能使用session认证
      config.headers['X-User-Id'] = userId
    }
    
    // 确保发送cookies（用于session认证）
    config.withCredentials = true
    
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    // 统一处理响应数据，返回后端的数据格式
    return response.data
  },
  error => {
    // 统一处理错误
    console.error('API请求错误:', error)
    if (error.response?.status === 401) {
      // 处理未授权错误，比如跳转到登录页
      localStorage.removeItem('token')
      // 可以在这里添加路由跳转逻辑
    }
    return Promise.reject(error)
  }
)

// API接口定义
export const userAPI = {
  // 用户登录
  login: (data) => api.post('/user/login', data),
  
  // 获取用户信息
  getUserInfo: (userId) => {
    if (userId === 'login') {
      return api.get('/user/get/my')
    }
    return api.get(`/user/${userId}`)
  },
  
  // 获取当前登录用户信息
  getCurrentUser: () => api.get('/user/get/login'),
  
  // 更新用户信息
  updateUserInfo: (data) => api.post('/user/update/my', data)
}

export const categoryAPI = {
  // 获取分类列表
  getList: () => api.get('/categories/list')
}

export const articleAPI = {
  // 获取文章列表
  getList: (params) => {
    const { current = 1, size = 20, categoryId } = params || {}
    let url = `/articles/list/page?current=${current}&size=${size}`
    if (categoryId) {
      url += `&categoryId=${categoryId}`
    }
    return api.get(url)
  },
  
  // 获取文章详情
  getDetail: (id) => api.get(`/articles/get?id=${id}`),
  
  // 写文章（简化版）
  write: (data) => api.post('/articles/write', data)
}

export const tagAPI = {
  // 获取热门标签
  getHotTags: (limit = 10) => api.get(`/tags/hot?limit=${limit}`),
  
  // 获取所有标签列表
  getList: () => api.get('/tags/list')
}

export const commentAPI = {
  // 获取评论列表
  getList: (params) => {
    const { current = 1, size = 20, articleId } = params || {}
    let url = `/comments/list/page?current=${current}&size=${size}`
    if (articleId) {
      url += `&articleId=${articleId}`
    }
    return api.get(url)
  },
  
  // 添加评论
  add: (data) => api.post('/comments/add', data),
  
  // 删除评论
  delete: (id) => api.delete(`/comments/delete/${id}`)
}

export const mediaAPI = {
  // 获取媒体文件列表
  getMedia: (params) => {
    const { current = 1, size = 20 } = params || {}
    return api.get(`/media/list?page=${current}&size=${size}`)
  },
  
  // 上传媒体文件
  uploadMedia: (formData) => api.post('/media/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }),
  
  // 删除媒体文件
  deleteMedia: (id) => api.delete(`/media/delete/${id}`),
  
  // 批量删除媒体文件
  deleteMultipleMedia: (ids) => api.post('/media/batch-delete', { ids })
}

export const settingsAPI = {
  // 获取系统设置
  getSettings: () => api.get('/settings'),
  
  // 更新系统设置
  updateSettings: (settingsData) => api.put('/settings', settingsData),
  
  // 上传Logo
  uploadLogo: (formData) => api.post('/settings/upload-logo', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 导出axios实例，供特殊情况使用
export { api }

// 默认导出所有API
export default {
  user: userAPI,
  category: categoryAPI,
  article: articleAPI,
  tag: tagAPI,
  comment: commentAPI,
  media: mediaAPI,
  settings: settingsAPI,
  api
}